<template>
	<view class="editInfo">
		<view class="form-item">
			<view class="label">
				<text>企业LOGO</text>
				<text class="require">*</text>
			</view>
			<view class="vlaue" @tap="chooseImg">
				<image :src="form.companyLogo" mode=""></image>
			</view>
		</view>
		<view class="form-item">
			<view class="label">
				<text>公司</text>
				<text class="require">*</text>
			</view>
			<view class="vlaue">
				<input v-model="form.companyName" type="text" placeholder="请输入">
			</view>
		</view>
		<view class="form-item">
			<view class="label">
				<text>行业</text>
				<text class="require">*</text>
			</view>
			<view class="vlaue">
				<!-- <view class="select">
					<text class="placeholder">请选择</text>
					<uni-icons type="right"></uni-icons>
				</view> -->
				<!-- <input v-model="form.industry" type="text" placeholder="请输入"> -->
				<picker @change="bindPickerChange" :range="typeList" range-key="value">
					<view v-if="form.industry.value">{{form.industry.value}}</view>
					<view v-else class="placeholder">请选择</view>
				</picker>
			</view>
		</view>
		<view class="form-item">
			<view class="label">
				<text>员工人数</text>
				<text class="require">*</text>
			</view>
			<view class="vlaue">
				<!-- <view class="select">
					<text class="placeholder">请选择</text>
					<uni-icons type="right"></uni-icons>
				</view> -->
				<input v-model="form.employeeNumber" type="text" placeholder="请输入">
			</view>
		</view>
		<view class="form-item align-start">
			<view class="label">
				<text>服务范围</text>
				<text class="require">*</text>
			</view>
			<view class="vlaue">
				<view class="tags-box">
					<view v-for="(item, index) in form.serviceScope" :key="index" class="tags">{{ item }}<icon type="clear" size="14" @tap="removeTags(index)"/></view>
					<view class="add-tags-btn" @tap="addTags">+ 新建标签</view>
				</view>
			</view>
		</view>
		<view class="form-item">
			<view class="section">
				<view class="title">口号</view>
				<textarea v-model="form.slogan" cols="30" rows="10" placeholder="20字以内"></textarea>
			</view>
		</view>
		<view class="form-item">
			<view class="section">
				<view class="title">
					<text>地址<text class="require">*</text></text>
					<text class="text-btn" @tap="selectAddress">获取地址</text>
				</view>
				<!-- <textarea v-model="form.address" cols="30" rows="10"></textarea> -->
				<view class="address">{{form.address.address}}</view>
			</view>
		</view>
		<view class="btn" @tap="submit">保存</view>
		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose"  mode="input" title="新建标签" v-model="tags"
				placeholder="请输入" @confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup>
		<poster ref="poster" :list="list" background-color="#FFF" :width="563" :height="450"
		            @on-success="posterSuccess" @on-error="posterError"></poster>
	</view>
</template>

<script>
import http from '@/utils/http.js'
import Poster from '../../components/zhangyuhao-poster/Poster.vue'
export default {
	components: {
		Poster
	},
	data() {
		return {
			form: {
			    "companyLogo": "",
			    "companyName": "",
			    "industry": "",
			    "employeeNumber": "",
			    "serviceScope": "",
			    "slogan": "",
			    "address": ""
			},
			tags: '',
			list: [],
			info: {}
		}
	},
	onLoad() {
		this.getType()
		this.getData()
	},
	methods: {
		posterSuccess(url) {
			console.log(url)			
			uni.uploadFile({
			  url: `https://ywtmp.hnwytkj.com/app-api/infra/file/upload?path=images/${this.info.companyProfileDO.id}/shareCard.jpg`,
			  filePath: url,
			  name: 'file',
			  success: (uploadFileRes) => {
				uni.hideLoading()
				uni.showToast({
					title: '保存成功',
					icon: "success"
				});
			  },
			  fail: (res) => {
				  console.log(res)
			  }
			});	
		},
		posterError(err) {
			uni.hideLoading()
		},
		createdPoster() {
			this.list = [{
					type: 'image',
					path: 'https://ywtmp.hnwytkj.com/static/images/shareCardBj.jpg',//this.info.userProfileDO.avatar,
					x: 0,
					y: 0,
					width: 563,
					height: 450
				},
				{
					type: 'text',
					text: this.info.userProfileDO.realName || '',
					x: 85,
					y: 85,
					size: 24,
					color: '#493b25'
				},
				{
					type: 'text',
					text: this.form.companyName || '',
					x: 85,
					y: 120,
					size: 16,
					color: '#766f5c'
				},
				{
					type: 'image',
					path: this.info.userProfileDO.avatar || '',
					x: 356,
					y: 71,
					shape: 'circle',
					width: 110,
					height: 110
				},
				{
					type: 'text',
					text: this.info.userProfileDO.phoneNumber,
					x: 110,
					y: 210,
					size: 16,
					color: '#766f5c'
				},
				{
					type: 'textarea',
					text: this.form.address ? this.form.address.address : '',
					x: 110,
					y: 260,
					width: 395,
					height: 160,
					size: 16,
					color: '#766f5c'
				}
			];
			return new Promise((resolve, reject) => {
				// 生成图片
				this.$nextTick(() => {
					// 要放在$nextTick()里，不然会空白
					this.$refs.poster.create();	
					resolve()
				})
			})
		},
		bindPickerChange(e) {
			console.log(e)
			this.form.industry = this.typeList[e.detail.value]
		},
		editCard() {
			uni.navigateTo({
				url: '/pagesA/edit/editCard'
			})
		},
		removeTags(index) {
			this.form.serviceScope.splice(index, 1)
		},
		addTags() {
			this.tags = ''
			this.$refs.inputDialog.open()
			this.$refs.inputClose.setVal('') //.modelValue = ''
			console.log(this.$refs.inputClose)
		},
		dialogInputConfirm() {
			this.form.serviceScope.push(this.tags)
			this.$refs.inputDialog.close()
			this.tags = ''
		},
		getMapLocation() {
		    uni.chooseLocation({
		        success: (res) => {
		            console.log(res);
		            // 处理返回的位置信息
					this.form.address = {
						name: res.name,
						address: res.address,
						latitude: res.latitude,
						longitude: res.longitude
					}
		        },
		        fail: () => {
		            // 处理失败情况，可能需要再次请求授权
		        }
		    });
		},
		selectAddress() {
			// uni.getSetting({
			//     success: (res) => {
			//         if (!res.authSetting['scope.userLocation']) {
			//             uni.showModal({
			//                 title: "是否授权当前位置",
			//                 content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
			//                 success: (tip) => {
			//                     if (tip.confirm) {
			//                         uni.openSetting({});
			//                     }
			//                 }
			//             });
			//         } else {
			//             this.getMapLocation();
			//         }
			//     }
			// })
			this.getMapLocation();
		},
		upload(filePath) {
			const fileName = filePath.split('/').pop()
			uni.uploadFile({
			      url: `https://ywtmp.hnwytkj.com/app-api/infra/file/upload?path=${fileName}`, //仅为示例，非真实的接口地址
			      filePath,
			      name: 'file',
			      // formData: {},
			      success: (uploadFileRes) => {
					const res = JSON.parse(uploadFileRes.data)
			        console.log(uploadFileRes.data);
					if (res.code === 0) {
						this.form.companyLogo = res.data
					}
			      },
				  fail: (res) => {
					  console.log(res)
				  }
			    });
		},
		chooseImg() {
			uni.chooseImage({
			    count: 1, //默认9
			    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			    sourceType: ['album'], //从相册选择
				success: (res) => {
					console.log(res.tempFilePaths)
					this.upload(res.tempFilePaths[0])
					// for (let i = 0; i < res.tempFilePaths.length; i++) {
					// 	const item = res.tempFilePaths[i]							
					// 	const ossPath = await this.upload(item)
					// 	this.imgList.push(ossPath)
					// 	console.log(this.imgList)
					// }
				}
			});				
		},
		submit() {
			if (!this.form.companyLogo) {
				uni.showToast({
					title: '请上传logo',
					icon: 'none'
				});
				return false;
			}
			if (!this.form.companyName) {
				uni.showToast({
					title: '请填写公司名称',
					icon: 'none'
				});
				return false;
			}
			if (!this.form.industry) {
				uni.showToast({
					title: '请选择行业',
					icon: 'none'
				});
				return false;
			}
			if (!this.form.employeeNumber) {
				uni.showToast({
					title: '请填写员工人数',
					icon: 'none'
				});
				return false;
			}
			if (!this.form.serviceScope) {
				uni.showToast({
					title: '请填写服务范围',
					icon: 'none'
				});
				return false;
			}
			// if (!this.form.slogan) {
			// 	uni.showToast({
			// 		title: '请填写口号'
			// 	});
			// 	return false;
			// }
			if (!this.form.address) {
				uni.showToast({
					title: '请填写地址',
					icon: 'none'
				});
				return false;
			}
			uni.showLoading({
				title: '保存中...',
				mask: true
			})
			http({
				url: 'card/user-profile/company/update',
				method: 'put',
				data: {
					...this.form,
					industry: JSON.stringify(this.form.industry),
					address: JSON.stringify(this.form.address),
					// address: JSON.stringify({
					// 	address: "湖南省长沙市岳麓区金星北路一段517号",
					// 	latitude: 28.23529,
					// 	longitude: 112.93134,
					// 	// name: "长沙市岳麓区人民政府(含光路南)"
					// }),
					serviceScope: this.form.serviceScope.join(',')
				}
			}).then(res => {				
				if(res.code === 0) {
					if ((JSON.stringify(this.form.address) !== this.info.companyProfileDO.address) || (this.form.companyName !== this.info.companyProfileDO.companyName)) {
						this.createdPoster()
					} else {
						uni.showToast({
							title: '保存成功',
							icon: "success"
						});
					}					
				}
			})
		},
		getType() {			
			http({
				url: 'system/dict-data/type?type=business'
			}).then(res => {				
				if(res.code === 0) {
					this.typeList = res.data
				}
			})
		},
		getData() {
			http({
				url: 'card/user-profile/get'
			}).then(res => {				
				if(res.code === 0) {
					this.info = JSON.parse(JSON.stringify(res.data))
					this.form = {
						// ...res.data.companyProfileDO,
						companyLogo: res.data.companyProfileDO.companyLogo,
						companyName: res.data.companyProfileDO.companyName,
						employeeNumber: res.data.companyProfileDO.employeeNumber,
						slogan: res.data.companyProfileDO.slogan,
						industry: res.data.companyProfileDO.industry ? JSON.parse(res.data.companyProfileDO.industry) : {},
						address: res.data.companyProfileDO.address ? JSON.parse(res.data.companyProfileDO.address) : {},
						serviceScope: res.data.companyProfileDO.serviceScope ? res.data.companyProfileDO.serviceScope.split(',') : []
					}
				}
			})		
		}
	},
}
</script>

<style lang="scss" scoped>
	.editInfo {
		background: #F0F0F4;
		min-height: 100vh;
		padding: 20rpx 20rpx calc(20rpx + var(--safe-area-inset-bottom));
		box-sizing: border-box;
		font-family: PingFang SC;
		.form-item {
			background: #FFFFFF;
			border-radius: 40rpx;
			padding: 38rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-weight: 500;
			font-size: 28rpx;
			color: #333333;
			margin-bottom: 20rpx;
			&.align-start {
				align-items: flex-start;
				.label {
					line-height: 70rpx;
				}
			}
			.label {
				display: flex;
				align-items: center;
				margin-right: 30rpx;
				.require {
					font-weight: bold;
					color: #FF6060;
				}
			}
			.vlaue {
				flex: 1;
				font-weight: bold;
				font-size: 28rpx;
				color: #333333;
				text-align: right;
				image {
					width: 130rpx;
					height: 130rpx;
					// background: #ECECEC;
					border-radius: 20rpx;
				}
				.placeholder {
					color: #626161;
				}
				input {
					width: 100%;
					text-align: right;
				}
				.select {
					display: flex;
					align-items: center;
					justify-content: flex-end;
					.placeholder {
						color: #626161;
					}
				}
				.tags-box {
					display: flex;
					align-items: center;
					flex-wrap: wrap;
					.tags {
						height: 70rpx;
						line-height: 70rpx;
						background: #EAFBF5;
						border-radius: 35rpx;
						font-weight: 500;
						font-size: 28rpx;
						color: #17B185;
						padding: 0 34rpx;
						margin-right: 20rpx;
						margin-bottom: 20rpx;
						display: flex;
						align-items: center;
						icon {
							line-height: 0;
							margin-left: 20rpx;
						}
					}
					.add-tags-btn {
						width: 207rpx;
						height: 70rpx;
						line-height: 70rpx;
						text-align: center;
						background: #E6ECFF;
						border-radius: 35rpx;
						font-weight: 500;
						font-size: 28rpx;
						color: #4B73FF;
						border: 1rpx dashed #4B73FF;
						box-sizing: border-box;
						margin-bottom: 20rpx;
					}
				}
			}
			.section {
				flex: 1;
				.title {
					font-weight: 500;
					font-size: 28rpx;
					color: #333333;
					margin-bottom: 25rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					.text-btn {
						font-weight: 500;
						font-size: 28rpx;
						color: #4B73FF;
					}
					.require {
						font-weight: bold;
						color: #FF6060;
					}
				}
				// textarea {
				.address {
					font-weight: 500;
					font-size: 28rpx;
					// color: #CCCCCC;
					color: #333333;
					border-radius: 10rpx;
					border: 1rpx solid #EEEEEE;
					width: 100%;
					height: 130rpx;
					box-sizing: border-box;
					padding: 28rpx 24rpx;
					&::placeholder {
						color: #CCCCCC;
					}
				}
			}
		}
		.btn {
			height: 90rpx;
			line-height: 90rpx;
			text-align: center;
			background: #4B73FF;
			border-radius: 20rpx;
			font-weight: bold;
			font-size: 28rpx;
			color: #FFFFFF;
			margin-top: 42rpx;
		}
	}
</style>